package com.dz.mybatis;

import java.util.Date;

import org.apache.ibatis.reflection.MetaObject;

import com.baomidou.mybatisplus.mapper.MetaObjectHandler;
import com.dz.common.context.FacadeContext;
import com.dz.common.context.UserContextVO;
import com.dz.common.entity.AbstractOpEntity;
import com.dz.common.entity.IdEntity;
import com.dz.db.IdGenerator;

public class CommonFieldHandler extends MetaObjectHandler {

	private final IdGenerator idGenerator;

	public CommonFieldHandler(IdGenerator idGenerator) {
		this.idGenerator = idGenerator;
	}

	@Override
	public void insertFill(MetaObject metaObject) {
		UserContextVO userContextVO = FacadeContext.getCurrentUser();
		Object obj = metaObject.getOriginalObject();
		if (obj instanceof IdEntity) {
			IdEntity idEntity = (IdEntity) obj;
			if (idEntity.getId() == null){
				Long id=idGenerator.generatorId(obj.getClass());
				metaObject.setValue("id",id);
			}
		}
		if (obj instanceof AbstractOpEntity) {
			metaObject.setValue("createBy", userContextVO.getLoginId());
			metaObject.setValue("createDate", new Date());
			metaObject.setValue("updateBy", userContextVO.getLoginId());
			metaObject.setValue("updateDate", new Date());
		}
	}

	public void updateFill(MetaObject metaObject) {
		UserContextVO userContextVO = FacadeContext.getCurrentUser();
		Object obj = metaObject.getOriginalObject();
		if (userContextVO != null) {
			if (obj instanceof AbstractOpEntity) {
				metaObject.setValue("updateBy", userContextVO.getLoginId());
				metaObject.setValue("updateDate", new Date());
			}
		}
	}
}
